import { Table, message, Popconfirm, Space, Modal, Row, Col, Form, InputNumber, Checkbox, Button } from "antd";
import { useModel, Outlet, useLocation, history } from "umi";
import { Card as SemiCard, ButtonGroup, List } from "@douyinfe/semi-ui";
import { IconRefresh, IconPlusCircle, IconDelete, IconEdit } from "@douyinfe/semi-icons";
import { useReactive } from "ahooks";
import { useEffect } from "react";

import useRoles from "../../hooks/useRoles";
import useCustomers from "../../hooks/useCustomers";

const EditAuthApply = ({ record, reloadData }) => {
    const [form] = Form.useForm();
    const { loadRoles, roles, getRolesPrice } = useRoles();
    const { authorizeApply } = useCustomers();
    const { baseInfo } = useModel("person.info");
    const { onCloseGlobalModal } = useModel("global.modal");

    const state = useReactive({
        aggregate: null,
    });

    useEffect(() => {
        loadRoles();
    }, []);

    const loadRolesPrice = async (roles) => {
        let res = await getRolesPrice(roles);
        if (res?.length > 0) {
            state.aggregate = res.reduce((prev, next) => {
                let aiSdpr = (prev.aiSdpr || 0) + parseFloat(next.aiSdpr || 0);
                let aiSppr = (prev.aiSppr || 0) + parseFloat(next.aiSppr || 0);
                let aiEcpr = (prev.aiEcpr || 0) + parseFloat(next.aiEcpr || 0);
                return { aiSdpr, aiSppr, aiEcpr };
            }, {});
        }
    };

    const onCheckboxChange = async (roles) => {
        loadRolesPrice(roles);
    };

    useEffect(() => {
        if (record?.oaaaUuid) {
            let aiEcpr = record.oaaaEcpr / record.oaaaMont;
            let aiSppr = record.oaaaSppr / record.oaaaMont;
            let grossProfit = record.oaaaEcpr - record.oaaaSppr;
            form.setFieldsValue({ aiEcpr, aiSppr, grossProfit });
            loadRolesPrice(record.oaaaRole);
        }
    }, [record]);

    const onValuesChange = async (changedValues, allValues) => {
        if (changedValues?.oaaaRole) {
            await loadRolesPrice(allValues.oaaaRole);
            let aiSppr = state.aggregate.aiSppr;
            let oaaaSppr = allValues.oaaaMont * (state.aggregate.aiSppr || 0);
            let grossProfit = allValues.oaaaEcpr - oaaaSppr;
            form.setFieldsValue({ aiSppr, oaaaSppr, grossProfit });
        } else {
            let oaaaEcpr = allValues.oaaaMont * allValues.aiEcpr;
            let oaaaSppr = allValues.oaaaMont * allValues.aiSppr;
            let grossProfit = oaaaEcpr - oaaaSppr;
            form.setFieldsValue({ oaaaEcpr, oaaaSppr, grossProfit });
        }
    };

    const onFinish = async (values) => {
        values.oaaaSdpr = state.aggregate.aiSdpr;
        values.apInfo = { uuid: baseInfo.uuid, name: baseInfo.realName };

        let exInfo = record.exInfo;
        exInfo.push({
            uuid: baseInfo.uuid,
            name: baseInfo.realName,
            time: new Date().getUTCTime(),
            reason: "",
            status: "重新申请",
        });

        values.exInfo = exInfo;

        authorizeApply({ ...record, ...values }, (res) => {
            if (res) {
                message.success("成功提交");
                reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <Form name="change-password" form={form} layout="vertical" onFinish={onFinish} onValuesChange={onValuesChange} style={{ padding: "10px 20px" }} initialValues={record}>
            <Form.Item label="可授权角色" name="oaaaRole" rules={[{ required: true }]}>
                <Checkbox.Group options={roles} onChange={onCheckboxChange} />
            </Form.Item>

            <Row gutter={10}>
                <Col span={8}>
                    <Form.Item label="授权月数" name="oaaaMont" rules={[{ required: true }]}>
                        <InputNumber min={1} controls={false} style={{ width: "100%" }} />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item label="客户结算价格/月" name="aiEcpr" rules={[{ required: true }]}>
                        <InputNumber prefix="￥" controls={false} style={{ width: "100%" }} />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item label="平台结算价格/月" name="aiSppr" style={{ display: "none" }}>
                        <InputNumber readOnly prefix="￥" controls={false} style={{ width: "100%" }} />
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={10}>
                <Col span={8}>
                    <Form.Item label="客户结算金额" name="oaaaEcpr" rules={[{ required: true }]}>
                        <InputNumber readOnly prefix="￥" controls={false} style={{ width: "100%" }} />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item label="平台结算金额" name="oaaaSppr" rules={[{ required: true }]} style={{ display: "none" }}>
                        <InputNumber readOnly prefix="￥" controls={false} style={{ width: "100%" }} />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item label="毛利" name="grossProfit" style={{ display: "none" }}>
                        <InputNumber readOnly min={0} prefix="￥" controls={false} style={{ width: "100%" }} />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item>
                <Space>
                    <Button loading={false} type="primary" htmlType="submit">
                        保存并提交审核
                    </Button>
                    <Button loading={false} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    );
};

export default EditAuthApply;
